﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Geolocation;
using Bing.Maps;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.ApplicationModel.DataTransfer;
using BingMapsGeolocationTemplate.Data;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace BingMapsGeolocationTemplate
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : BingMapsGeolocationTemplate.Common.LayoutAwarePage
    {
        Geolocator geolocator;
        LocationIcon locationIcon;
        private DataTransferManager dataTransferManager;

        PlacesDataItem selectedItem;

        private bool isGroup = true;

        public MainPage()
        {
            this.InitializeComponent();

            //Geolocalização
            geolocator = new Geolocator();
            locationIcon = new LocationIcon();
            map.Children.Add(locationIcon);
            geolocator.PositionChanged += new Windows.Foundation.TypedEventHandler<Geolocator, PositionChangedEventArgs>(geolocator_PositionChanged);

            //Adicionar locais na lista
            //Local l = new Local("Colégio Sagrado Coração de Jesus", -22.427809, -45.449750);
            //locais.Add(l);
            //lista.ItemsSource = locais;
            
            //Adicionar pushpins dinamicamente via código
            Pushpin cscj = new Pushpin();
            Location location = new Location(-22.427809,-45.449750);
            MapLayer.SetPosition(cscj, location);
            map.Children.Add(cscj);



            foreach (var group in PlacesDataSource.GetGroups("AllGroups"))
            {
                foreach (var item in group.Items)
                {
                    Pushpin p = new Pushpin();
                    Location l = new Location(item.Latitude, item.Longitude);
                    MapLayer.SetPosition(p, l);
                    map.Children.Add(p);
                }
            }
        }

        private async void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            // Need to set map view on UI thread.
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(
                () =>
                {
                    displayPosition(this, args);
                }));
        }

        private void displayPosition(object sender, PositionChangedEventArgs args)
        {
            Location location = new Location(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
            MapLayer.SetPosition(locationIcon, location);
            map.SetView(location, 15.0f);
        }

        private async void UnifeiTapped(object sender, TappedRoutedEventArgs e)
        {
            MessageDialog dialog = new MessageDialog("Bem-vindo à UNIFEI");
            await dialog.ShowAsync();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var sampleDataGroups = PlacesDataSource.GetGroups("AllGroups");
            this.DefaultViewModel["Groups"] = sampleDataGroups;

            // Register the current page as a share source.
            this.dataTransferManager = DataTransferManager.GetForCurrentView();
            this.dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);
        }

        private void lista_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (isGroup)
            {
                var groupId = ((PlacesDataGroup)e.ClickedItem).UniqueId;
                var group = PlacesDataSource.GetGroup(groupId.ToString());
                this.DefaultViewModel["Group"] = group;
                this.DefaultViewModel["Items"] = group.Items;
                pageTitle.Text = group.Title;
                listaGrupos.Visibility = Visibility.Collapsed;
                listaItems.Visibility = Visibility.Visible;
                backButton.IsEnabled = true;
                isGroup = false;
            }
            else
            {
                selectedItem = ((PlacesDataItem)e.ClickedItem);
                Location location = new Location(selectedItem.Latitude, selectedItem.Longitude);
                map.SetView(location, 17.0f);
            }
        }

        protected override void GoBack(object sender, RoutedEventArgs e)
        {
            var sampleDataGroups = PlacesDataSource.GetGroups("AllGroups");
            this.DefaultViewModel["Groups"] = sampleDataGroups;
            pageTitle.Text = "Locais";
            listaGrupos.Visibility = Visibility.Visible;
            listaItems.Visibility = Visibility.Collapsed;
            backButton.IsEnabled = false;
            isGroup = true;
        }

        //ShareSource
        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            // Call the scenario specific function to populate the datapackage with the data to be shared.
            if (GetShareContent(e.Request))
            {
                // Out of the datapackage properties, the title is required. If the scenario completed successfully, we need
                // to make sure the title is valid since the sample scenario gets the title from the user.
                if (String.IsNullOrEmpty(e.Request.Data.Properties.Title))
                {
                    e.Request.FailWithDisplayText("Erro");
                }
            }
        }

        //ShareSource
        protected bool GetShareContent(DataRequest request)
        {
            bool succeeded = false;

            string dataPackageText = "Teste";
            string url = "http://www.bing.com/maps/default.aspx?q=";
            if (selectedItem != null)
            {
                DataPackage requestData = request.Data;
                requestData.Properties.Title = selectedItem.Title;
                url += selectedItem.Latitude + "," + selectedItem.Longitude;
                requestData.Properties.Description = url; // The description is optional.
                dataPackageText = url;
                requestData.SetText(dataPackageText);
                succeeded = true;
            }
            else
            {
                request.FailWithDisplayText("Selecione um item da lista e tente novamente!");
            }
            return succeeded;
        }

        private void Home_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));  
        }
    }
}
